﻿using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NetMQ;

namespace Lawn.AppServer
{
    public class PubHandler:IPubHandler
    {

        private ILogger<PubHandler> logger;
        private ISerializeProvider serializeProvider;
        public PubHandler(ILogger<PubHandler> _logger,
            ISerializeProvider _serializeProvider
            )
        {
            this.logger = _logger;
            this.serializeProvider = _serializeProvider;
        }

        public Task Message<T>(NetMQSocket socket, TopicType topicType, T t)
        {
            if (topicType.Next&&!string.IsNullOrEmpty(topicType.NextTopic))
            {
               // string pub_msg = $"im send {topicType.NextTopic}";

                byte[] msg = null;
                if (typeof(T) != typeof(byte[]))
                {
                    msg = serializeProvider.Serialize(t);
                }
                else
                {
                    msg = t as byte[];
                }
                socket.SendMoreFrame(topicType.NextTopic).SendFrame(msg);
              
                logger.LogInformation($"{Encoding.UTF8.GetString(msg)}");
            }
         
            return  Task.CompletedTask;
            
        }
    }
}